<template>
  <div class="formulaDetail">
    <el-card class="lh28">
      <el-form ref="detail" :model="detail" :rules="rules" label-position="left">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item size="mini" label="配方名称" prop="formulaName">
              <el-select
                v-model="detail.formulaName"
                filterable
                remote
                reserve-keyword
                class="w280"
                clearable
                :disabled="nameType == '详情'"
                placeholder="请输入配方名称"
                :loading="loading"
                :remote-method="remoteMethod"
                @change="changeName"
              >
                <el-option v-for="item in options.drugs" :key="item.id" :label="item.drugName" :value="item.drugName">
                  <span style="float: left">{{ item.drugName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.drugCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="mini" label="三方编码">
              <el-input v-model="detail.drugThirdCode" disabled clearable class="w280" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="mini" label="药品编码">
              <el-input v-model="detail.drugCode" disabled clearable class="w280" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="mini" label="版本号">
              <el-input v-model="detail.versionNo" disabled clearable class="w280" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="mini" label="价格院区">
              <el-select v-model="detail.yardIds" filterable clearable placeholder="请选择" value-key="id" class="w200">
                <el-option v-for="item in options.yard" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-button type="primary" icon="el-icon-search" @click="getPrice">搜索</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="mini" label="科室维度">
              <MultipleSelect ref="dept" v-model="dimension.deptIds" name="dept" width="200" :options="multipleSelectOptions" multiple :data="options.dept" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="mini" label="疾病维度">
              <MultipleSelect ref="disease" v-model="dimension.diseaseIds" name="disease" width="200" :options="multipleSelectOptions" multiple :data="options.disease" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="mini" label="医生维度">
              <MultipleSelect ref="doctor" v-model="dimension.doctorIds" name="doctor" width="200" :options="doctorMultipleSelectOptions" multiple :data="options.doctor" />
            </el-form-item>
          </el-col>

          <el-col :span="18">
            <el-form-item size="mini">
              <el-button v-if="nameType == '新增'" type="primary" size="small" @click="createDetail()">提 交</el-button>
              <el-button v-if="nameType == '修改'" type="primary" size="small" @click="createDetail()">保存</el-button>
              <el-button v-if="nameType == '修改'" type="primary" size="small" @click="createDetail('new')">保存并生成新版本</el-button>
              <el-button size="small" @click="returnUpper">返 回</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="mt10 detailBox">
      <el-tabs v-model="editableTabsValue" type="card" :closable="nameType != '详情'" @tab-remove="removeTab" @tab-click="tabClick">
        <el-tab-pane v-for="(item, index) in editableTabs" :key="index" :label="item.title" :name="index + ''" />
      </el-tabs>
      <el-button v-if="nameType != '详情'" class="addBtn" type="warning" icon="el-icon-plus" circle @click="addTab" />
      <el-form ref="tabForm" :model="tabForm" :rules="tabFormFules" label-position="left">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item size="mini" label="剂型" prop="medicamentTypeId">
              <el-select v-model="tabForm.medicamentTypeId" placeholder="请选择" value-key="id" class="w280" :disabled="nameType == '详情'" @change="dosageChange">
                <el-option v-for="opt in options.dosage" :key="opt.id" :label="opt.dictValue" :value="opt.id" :disabled="opt.disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item size="mini" label="治疗类型" prop="cureType">
              <el-select v-model="tabForm.cureType" :disabled="nameType == '详情'" placeholder="请选择" value-key="id" class="w280">
                <el-option label="治疗" :value="1" />
                <el-option label="调理" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item size="mini" label="单位" prop="unitCode">
              <el-select v-model="tabForm.unitCode" placeholder="请选择" value-key="id" :disabled="nameType == '详情'" class="w280" @change="changeUnitCode">
                <el-option v-for="item in options.drugUnitName" :key="item.id" :label="item.drugUnitName" :value="item.id + ''" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item size="mini" label="换算关系" prop="unitCoefficient">
          1剂 =
          <el-input v-model="tabForm.oneMedication" clearable class="w80" :disabled="nameType == '详情'" @change="(value) => changeMedicament(value, 'oneMedication')" />
          付 =
          <el-input v-model="tabForm.oneBag" clearable class="w80" :disabled="nameType == '详情'" @change="(value) => changeMedicament(value, 'oneBag')" />
          {{ tabForm.drugUnitName || '' }}/次 *
          <el-input v-model="tabForm.oneNumDay" clearable class="w80" :disabled="nameType == '详情'" @change="(value) => changeMedicament(value, 'oneNumDay')" />
          次/日 *
          <el-input v-model="tabForm.days" clearable class="w80" :disabled="nameType == '详情'" @change="(value) => changeMedicament(value, 'days')" />
          天 =
          <el-input v-model="tabForm.unitCoefficient" clearable class="w80" disabled @change="(value) => changeMedicament(value, 'unitCoefficient')" />
          {{ tabForm.drugUnitName || '' }}
        </el-form-item>
        <!-- <el-row>
          <el-col :span="6">
            <el-form-item size="mini" label="药品名称">
              <el-select
                id="addGoodId"
                v-model="addGoodId"
                filterable
                remote
                reserve-keyword
                class="w280"
                clearable
                :disabled="nameType == '详情'"
                placeholder="请输入药品名称/助记码/药品编码/三方编码"
                :loading="loading"
                :remote-method="addRemoteMethod"
                @change="changeAddName"
                @keydown.enter.native="getDataByKeywords"
              >
                <el-option
                  v-for="item in options.addDrugs"
                  :key="item.id"
                  :label="item.drugName + '（' + item.drugCategoryName + '）'"
                  :value="item.drugCode"
                >
                  <span
                    style="float: left"
                  >{{ item.drugName }}（{{ item.drugCategoryName }}）</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.drugCode
                  }}</span>
                </el-option>
              </el-select>
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="openDialog"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item size="mini" label="每付用料数量">
              <el-input
                id="quantity"
                v-model="quantity"
                type="number"
                size="mini"
                class="w80"
                @input="quantityInput"
                @keydown.enter.native="addRow"
              />
              <el-button
                type="primary"
                style="margin-left: 10px"
                icon="el-icon-plus"
                @click="addRow"
              >添加</el-button>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <el-table :data="tabForm.formulaMedicamentDetailDTO" size="small" class="mt20" show-summary :summary-method="getSummaries" :cell-style="$style.cellStyle" :header-cell-style="$style.rowClass">
        <ElTableColumn v-if="nameType != '详情'" label="操作" width="230">
          <template slot-scope="{ $index }">
            <el-button type="primary" size="mini" @click="addRow($index)">增</el-button>
            <el-button v-show="tabForm.formulaMedicamentDetailDTO.length > 1" type="primary" size="mini" @click="delRow($index)">删</el-button>
            <el-button v-show="$index > 0" type="primary" size="mini" @click="sortRow($index, $index - 1)">升</el-button>
            <el-button v-show="$index < tabForm.formulaMedicamentDetailDTO.length - 1" type="primary" size="mini" @click="sortRow($index, $index + 1)">降</el-button>
          </template>
        </ElTableColumn>
        <ElTableColumn label="序号" type="index" width="50" />
        <ElTableColumn label="原料药品名称" width="300">
          <template slot-scope="{ row, $index }">
            <el-select
              id="addGoodId"
              :ref="'drugName' + $index"
              v-model="row.drugName"
              size="mini"
              filterable
              remote
              clearable
              reserve-keyword
              :disabled="nameType == '详情'"
              placeholder="名称/助记码/编码"
              :loading="loading"
              :remote-method="addRemoteMethod"
              @change="(e) => changeAddName(e, row, $index)"
              @keyup.native="handleDrugNameKeyup($event, $index)"
            >
              <el-option v-for="item in options.addDrugs" :key="item.id" :label="item.drugName + '（' + item.drugCategoryName + '）'" :value="item.drugCode">
                <span style="float: left">{{ item.drugName }}（{{ item.drugCategoryName }}）</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.drugCode }}</span>
              </el-option>
            </el-select>
          </template>
        </ElTableColumn>
        <ElTableColumn label="看诊可删减" prop="allowDeletion">
          <template slot-scope="{ row, $index }">
            <el-select :ref="'allowDeletion' + $index" v-model="row.allowDeletion" placeholder="请选择" @keyup.native="handleAllowDeletionKeyup($event, $index, row)">
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            </el-select>
          </template>
        </ElTableColumn>
        <ElTableColumn label="药品类型">
          <template slot-scope="{ row }">
            {{ row.drugTypeName || row.drug_type_name }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="数量规则" width="120">
          <template slot-scope="{ row, $index }">
            <el-select v-if="row.drugTypeName == '辅料' || row.drug_type_name == '辅料'" :ref="'quantityRule' + $index" v-model="row.quantityRule" clearable placeholder="请选择" @change="tableCount(row)" @keyup.native="handleQuantityRuleKeyup($event, $index, row)">
              <el-option v-for="item in options.dimensionTypes" :key="item.id" :label="item.dictValue" :value="item.id" />
            </el-select>
          </template>
        </ElTableColumn>
        <ElTableColumn label="属性" prop="attribute">
          <template slot-scope="{ row, $index }">
            <el-select :ref="'dimensionAttribute' + $index" v-model="row.attribute" placeholder="请选择" @keyup.native="handleDimensionAttributeKeyup($event, $index, row)">
              <el-option v-for="item in options.dimensionAttribute" :key="item.id" :label="item.dictValue" :value="item.id" />
            </el-select>
          </template>
        </ElTableColumn>
        <ElTableColumn label="药品编码" prop="drugCode" />
        <ElTableColumn label="三方编码" prop="drugThirdCode" />
        <ElTableColumn label="单位" prop="drugUnitName">
          <!-- <template slot-scope="{ row, $index }">
            <el-select :ref="'drugUnitName' + $index" v-model="row.drugUnitName" placeholder="请选择" value-key="id" :disabled="nameType == '详情'" @keyup.native="handleDrugUnitNameKeyup($event, $index,row)">
              <el-option v-for="item in options.drugUnitName" :key="item.id" :label="item.drugUnitName" :value="item.drugUnitName" />
            </el-select>
          </template> -->
        </ElTableColumn>
        <ElTableColumn label="每付用料数量" width="120">
          <template slot-scope="{ row, $index }">
            <el-input v-if="nameType != '详情'" :ref="'quantityInput' + $index" v-model="row.quantity" size="mini" class="w80" type="number" @change="quantityChnage(row)" @input="quantityInput(row)" @keyup.native="handleQuantityInputKeyup($event, $index, row)" @keydown.native="handleQuantityInputKeydown($event)" />
            <span v-else>{{ row.quantity }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="单价" prop="drugPrice">
          <template slot-scope="{ row }">
            {{ row.drugPrice || '-' }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="单付总金额" prop="payPrice" align="center">
          <template slot-scope="{ row }">
            {{ row.payPrice || '-' }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="总付数用料用量" prop="totalNum" align="center">
          <template slot-scope="{ row }">
            {{ row.totalNum || '-' }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="总付数总金额" prop="totalPrice" align="center">
          <template slot-scope="{ row }">
            {{ row.totalPrice || '-' }}
          </template>
        </ElTableColumn>
      </el-table>
    </el-card>
    <!-- 选择药品 -->
    <addGoods v-if="addGoodsShow" :goods-id="goods_id" :drug-type-codes="'10014'" @goodsList="addList" @closeAdd="addGoodsShow = false" />
  </div>
</template>
<script>
	import addGoods from '@/components/AddGoods';
	import { dictsPullList } from '@/api/dictionaries';
	import { yardPullList } from '@/api/courtyardAdmin';
	import { allDrugsList, unitList } from '@/api/drugs';
	import { getDrugList } from '@/api/drugs';
	import { formulaAdd, registerUpdate, registerDetail, selectPrice, dimensionQuery } from '@/api/formula';
	import { TimeSelect } from 'element-ui';
	class Options {
		drugs = [] // 配方
		yard = [] // 院区
		cureType = [] // 治疗类型
		dosage = [] // 剂型
		drugUnitName = [] // 单位
		addDrugs = [] // 药品
		dimensionAttribute = [] // 药品属性
		dimensionTypes = [] // 药品数量规则
		dept = [] // 科室维度
		disease = [] // 疾病维度
		doctor = [] // 医生维度
	}
	class Rules {
		formulaName = [{ required: true, message: '请选择配方名称', trigger: 'blur' }]
	}
	class TabFormFules {
		medicamentTypeId = [{ required: true, message: '请选择剂型', trigger: 'change' }]
		cureType = [{ required: true, message: '请选择治疗类型', trigger: 'change' }]
		unitCode = [{ required: true, message: '请选择单位', trigger: 'change' }]
		unitCoefficient = [{ required: true, message: '请输入换算方式', trigger: 'change' }]
	}
	class Detail {
		formulaName = '' // 配方名称
		drugThirdCode = '' // 三方编码
		drugCode = '' // 药品编码
		versionNo = '' // 版本号
		deptIds = []
		diseaseIds = []
		doctorIds = []
	}
	class TabForm {
		medicamentTypeId = '' // 剂型
		medicamentType = '' // 剂型
		cureType = '' // 治疗类型
		unitCode = '' // 单位
		drugUnitName = '' // 单位
		oneMedication = '' // 一剂付数
		oneBag = '' // 一次多少
		oneNumDay = '' // 一日几次
		days = '' // 多少天
		unitCoefficient = '' // 多少袋
		formulaMedicamentDetailDTO = []
	}
	class Good {
		allowDeletion = false
		attribute = ''
		attribute_remark = ''
		drugCode = ''
		drugCode1 = ''
		drugName = ''
		drugSpecName = ''
		drugThirdCode = ''
		drugTypeName = ''
		drugUnitName = ''
		drug_type_name = ''
		id = ''
		message = ''
		messageIncompatibility = ''
		messageOpposite = ''
		price = ''
		quantity = ''
		quantityRule = ''
		quantityRuleRemark = ''
		drugPrice = ''
		payPrice = ''
		totalNum = ''
		totalPrice = ''
	}
	export default {
		components: {
			addGoods
		},
		data() {
			return {
				multipleSelectOptions: {
					formatSelectAll: function name(params) {
						return '全部';
					},
					// filter: true, // 开启过滤
					multiple: true // 一行显示多个选项
				},
				doctorMultipleSelectOptions: {
					formatSelectAll: function name(params) {
						return '公共';
					},
					filter: true, // 开启过滤
					multiple: true // 一行显示多个选项
				},
				rules: new Rules(), // 表单校验
				options: new Options(), // 选项
				loading: false,
				detail: new Detail(),
				nameType: '',
				editableTabsValue: '0',
				editableTabs: [
					{
						title: '药剂'
					}
				],
				tabForm: new TabForm(),
				tabFormFules: new TabFormFules(),
				tabTable: [],
				addGoodId: '',
				addGoodItem: {},
				quantity: '',
				goods_id: [], // 药品id集合
				addGoodsShow: false, // 选择药品
				detailData: [],
				dimension: {
					deptIds: [],
					diseaseIds: [],
					doctorIds: []
				}
			};
		},
		watch: {
			editableTabsValue: {
				handler() {
					this.options.dosage = this.options.dosage.map((ele) => {
						ele.disabled = false;
						this.detailData.forEach((item, index) => {
							if (this.editableTabsValue != index && ele.id == item.medicamentTypeId) {
								ele.disabled = true;
							}
						});
						return ele;
					});
				}
			}
		},
		mounted() {
			this.nameType = this.$route.query.nameType;
			this.getOptions();
		},
		methods: {
			// 药品名称按键处理
			handleDrugNameKeyup($event, $index) {
				let refKey = '';
				switch ($event.keyCode) {
					case 39: // 右
						refKey = 'allowDeletion' + $index;
						break;
					case 37: // 左
						if ($index > 0) {
							refKey = 'quantityInput' + ($index - 1);
						}
						break;
					default:
						break;
				}
				if (refKey) {
					this.refBlur('drugName' + $index);
					this.refFocus(refKey);
				}
			},
			// 是否可删减按键处理
			handleAllowDeletionKeyup($event, $index, row) {
				console.log($event, $index);
				let refKey = '';
				switch ($event.keyCode) {
					case 39: // 右
						if (row.drugTypeName == '辅料' || row.drug_type_name == '辅料') {
							refKey = 'quantityRule' + $index;
						} else {
							refKey = 'dimensionAttribute' + $index;
						}
						break;
					case 37: // 左
						refKey = 'drugName' + $index;
						break;

					default:
						break;
				}
				if (refKey) {
					this.refBlur('allowDeletion' + $index);
					this.refFocus(refKey);
				}
			},
			// 数量规则按键处理
			handleQuantityRuleKeyup($event, $index) {
				console.log($event);
				let refKey = '';
				switch ($event.keyCode) {
					case 39: // 右
						refKey = 'dimensionAttribute' + $index;
						break;
					case 37: // 左
						refKey = 'allowDeletion' + $index;
						break;

					default:
						break;
				}
				if (refKey) {
					this.refBlur('quantityRule' + $index);
					this.refFocus(refKey);
				}
			},
			// 属性按键处理
			handleDimensionAttributeKeyup($event, $index, row) {
				let refKey = '';
				switch ($event.keyCode) {
					case 39: // 右
						refKey = 'quantityInput' + $index;
						break;
					case 37: // 左
						if (row.drugTypeName == '辅料' || row.drug_type_name == '辅料') {
							refKey = 'quantityRule' + $index;
						} else {
							refKey = 'allowDeletion' + $index;
						}
						break;
					default:
						break;
				}
				if (refKey) {
					this.refBlur('dimensionAttribute' + $index);
					this.refFocus(refKey);
				}
			},
			// 单位按键处理
			/* handleDrugUnitNameKeyup($event, $index) {
				let refKey = '';

				switch ($event.keyCode) {
					case 39: // 右
						refKey = 'quantityInput' + $index;
						break;
					case 37: // 左
						refKey = 'dimensionAttribute' + $index;
						break;

					default:
						break;
				}
				if (refKey) {
					this.refBlur('drugUnitName' + $index);
					this.refFocus(refKey);
				}
			}, */
			// 用料数量按键处理
			handleQuantityInputKeyup($event, $index) {
				console.log($event);
				let refKey = '';
				switch ($event.keyCode) {
					case 39: // 右
						if ($index <= this.tabForm.formulaMedicamentDetailDTO.length - 1) {
							refKey = 'drugName' + ($index + 1);
						}
						break;
					case 40: // 下
						refKey = 'quantityInput' + ($index + 1);
						break;
					case 38: // 上
						refKey = 'quantityInput' + ($index - 1);
						break;
					case 37: // 左
						refKey = 'dimensionAttribute' + $index;
						break;
					case 13: // enter
						if ($index === this.tabForm.formulaMedicamentDetailDTO.length - 1) {
							this.addRow($index);
						}
						refKey = 'drugName' + ($index + 1);
						break;

					default:
						break;
				}
				if (refKey) {
					this.refFocus(refKey);
				}
			},
			// 阻止默认的上下键改变数字效果
			handleQuantityInputKeydown($event) {
				switch ($event.keyCode) {
					case 40: // 下
						$event.preventDefault();
						break;
					case 38: // 上
						$event.preventDefault();
						break;
					default:
						break;
				}
			},
			refBlur(refKey) {
				this.$refs[refKey] && this.$refs[refKey].blur();
			},
			refFocus(refKey) {
				this.$nextTick(() => {
					this.$refs[refKey] && this.$refs[refKey].focus();
				});
			},
			async getDetail() {
				this.detail = new Detail();
				const { data } = await registerDetail({ id: this.$route.query.id });
				this.detail.drugThirdCode = data.drugThirdCode;
				this.detail.drugCode = data.drugCode;
				this.detail.formulaName = data.formulaName;
				this.detail.versionNo = data.versionNo;
				this.detailData = data.formulaMedicament.map((ele, index) => {
					ele.cureType = ele.cureTypeId;
					ele.formulaMedicamentDetailDTO = ele.formulaMedicamentDetail.map((ele) => {
						return {
							...ele,
							drugPrice: '',
							payPrice: '',
							totalNum: '',
							totalPrice: ''
						};
					});
					return ele;
				});
				this.editableTabs = this.detailData.map((ele) => {
					return { title: ele.medicamentType };
				});
				this.options.dosage = this.options.dosage.map((ele) => {
					ele.disabled = false;
					this.detailData.forEach((item, index) => {
						if (this.editableTabsValue != index && ele.id == item.medicamentTypeId) {
							ele.disabled = true;
						}
					});
					return ele;
				});
				this.editableTabsValue = '0';
				this.tabClick();
				this.remoteMethod(data.formulaName);
				// 回显维度信息
				let fieldArr = ['deptIds', 'diseaseIds', 'doctorIds'];
				data.dimensionListVO.forEach((item) => {
					this.dimension[fieldArr[item.dimension_type - 1]] = item.dimension_codes.split('/');
				});
			},
			async getOptions() {
				const { data } = await dictsPullList({
					dicTypes: ['medicamentType', 'cureType', 'dimensionAttribute', 'dimensionTypes', 'dimension', 'dimensionDeptIds']
				});
				this.options.dosage = data.medicamentType;
				this.options.cureType = data.cureType;
				this.options.dept = data.dimensionDeptIds.map((item) => {
					item.text = item.dictValue;
					item.value = item.id + '';
					return item;
				});
				this.options.disease = data.dimension.map((item) => {
					item.text = item.dictValue;
					item.value = item.id + '';
					return item;
				});
				let res_doctor = await dimensionQuery();
				this.options.doctor =
					res_doctor.data.list.map((item) => {
						item.text = item.person_name;
						item.value = item.person_id;
						return item;
					}) || [];
				this.options.dimensionAttribute = data.dimensionAttribute.map((item) => {
					item.id += '';
					return item;
				});
				this.options.dimensionTypes = data.dimensionTypes.map((item) => {
					item.id += '';
					return item;
				});
				const res = await unitList({});
				this.options.drugUnitName = res.data;
				const yard = await yardPullList({ yardTypeIds: [37, 38] });
				this.options.yard = yard ? yard.data : [];
				if (this.nameType == '新增') {
					this.detailData.push(new TabForm());
					this.tabForm = this.detailData[0];
					// 默认增加一行
					this.addRow(-1);
				} else {
					this.getDetail();
				}
			},
			// 搜索药品
			async remoteMethod(query) {
				if (query !== '') {
					this.loading = true;
					const drugs = await allDrugsList({
						drugs: query,
						drugTypeCode: '10015'
					});
					if (drugs?.data) {
						this.options.drugs = drugs.data;
					}
					this.loading = false;
				} else {
					this.options.drugs = [];
				}
			},
			// 改变药品
			changeName(e) {
				this.options.drugs.forEach((item) => {
					if (e == item.drugName) {
						this.detail.drugThirdCode = item.drugThirdCode;
						this.detail.drugCode = item.drugCode;
					}
				});
			},
			// 获取价格
			async getPrice(val) {
				let details = this.tabForm.formulaMedicamentDetailDTO.map((ele) => {
					return { drugCode: ele.drugCode };
				});
				const { data } = await selectPrice({
					yardId: this.detail.yardIds,
					medicamentType: this.tabForm.medicamentType,
					details: details
				});
				let priceObj = {};
				data.forEach((ele) => {
					priceObj[ele.drugCode] = this.common.centsToYuan(ele.drugPrice);
				});
				this.tabForm.formulaMedicamentDetailDTO.forEach((ele) => {
					ele.drugPrice = priceObj[ele.drugCode];
					this.tableCount(ele);
				});
			},
			tabClick() {
				this.tabForm = this.detailData[this.editableTabsValue];
				this.changeUnitCode(this.tabForm.unitCode);
				this.tabForm.formulaMedicamentDetailDTO.forEach((ele) => {
					this.tableCount(ele);
				});
			},
			// 删除药剂
			removeTab(index) {
				if (this.editableTabs.length == 1) return;
				this.editableTabs.splice(index, 1);
				this.detailData.splice(index, 1);
				if (this.editableTabsValue >= this.editableTabs.length) {
					this.editableTabsValue = '0';
					this.tabClick();
				}
			},
			// 新增药剂
			addTab() {
				this.$refs.tabForm.validate((valid) => {
					if (valid) {
						if (this.tabForm.formulaMedicamentDetailDTO.length == 0) {
							this.$notification('警告', 'warning', `请先增加商品信息`);
							let el = document.getElementById(`addGoodId`);
							el && el.focus();
							return;
						}
						this.editableTabs.push({
							title: '药剂'
						});
						this.detailData.push({
							...this.tabForm,
							formulaMedicamentDetailDTO: this.tabForm.formulaMedicamentDetailDTO.map((ele) => {
								return {
									...ele,
									drugPrice: '',
									payPrice: '',
									totalPrice: ''
								};
							}),
							medicamentTypeId: ''
						});
						this.editableTabsValue = this.editableTabs.length - 1 + '';
						this.tabClick();
					} else {
						this.$notification('警告', 'warning', `请先完善表单内容`);
					}
				});
			},

			// 选择剂型
			dosageChange(e) {
				this.options.dosage.forEach((item) => {
					if (e == item.id) {
						this.tabForm.medicamentType = item.dictValue;
						this.editableTabs[this.editableTabsValue].title = item.dictValue;
					}
				});
			},
			// 选择单位
			changeUnitCode(val) {
				this.options.drugUnitName.forEach((ele) => {
					if (val == ele.id) {
						this.tabForm.drugUnitName = ele.drugUnitName;
					}
				});
			},
			// 换算关系
			changeMedicament(value, type) {
				let reg = /^[1-9]\d*$/;
				let regP = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
				if (type == 'oneMedicamentPrice' && !regP.test(value)) {
					this.$notification('警告', 'warning', `请输入数字并最多保留两位小数`);
					this.editableTabs[this.editableTabsValue][type] = '';
				} else if (type != 'oneMedicamentPrice' && !reg.test(value)) {
					this.$notification('警告', 'warning', `请输入正整数`);
					this.tabForm[type] = '';
				}
				let oneBag = this.tabForm.oneBag; // （单位：袋）/次
				let oneNumDay = this.tabForm.oneNumDay; // 次/日
				let days = this.tabForm.days; // 天数
				let unitCoefficient = ''; // （单位：袋)
				if (oneBag && oneNumDay && days) {
					unitCoefficient = oneBag * oneNumDay * days;
					this.tabForm.unitCoefficient = unitCoefficient;
				} else {
					this.tabForm.unitCoefficient = '';
				}
				if (type == 'oneMedication') {
					this.tabForm.formulaMedicamentDetailDTO.forEach((ele) => {
						this.tableCount(ele);
					});
				}
			},

			// 搜索药品
			async addRemoteMethod(query) {
				if (query !== '') {
					this.loading = true;
					const drugs = await getDrugList({
						drugs: query,
						drugTypeCodes: ['10014', '10022']
					});
					this.options.addDrugs = drugs && drugs.data && drugs.data.list ? drugs.data.list : [];
					this.loading = false;
				} else {
					this.options.addDrugs = [];
				}
			},
			// 改变药品
			changeAddName(e, row, $index) {
				console.log(e, row);
				this.options.addDrugs.forEach((item) => {
					if (e == item.drugCode) {
						row = Object.assign(row, item);
						row.drugThirdCode = item.thirdCode;
						console.log(this.$refs);
						console.log('quantityInput' + $index);
					}
				});
			},

			quantityChange(val) {
				if (!val) return;
				let reg = /^(\+?[1-9][0-9]*)$/;
				if (!reg.test(val)) {
					this.$notification('警告', 'warning', `只能正整数`);
					this.quantity = '';
					return;
				}
			},
			quantityInput(param) {
				let isRow = typeof param === 'object';
				let value = isRow ? param.quantity : this.quantity;
				if (!value.length) {
					return;
				}
				value = Number(value.trim()) + '';
				// 最多输入一位小数
				value = value.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3');
				value = value.replace(/(\d{15})\d*/, '$1'); // 最多保留15位整数
				if (isRow) {
					param.quantity = value;
				} else if (typeof param === 'string') {
					this.quantity = value;
				}
			},
			// 回车事件
			// getDataByKeywords() {
			//   this.$nextTick(() => {
			//     let el = document.getElementById(`quantity`);
			//     el && el.focus();
			//   });
			// },
			// 新增商品
			addRow(index) {
				let item = new Good();
				this.tabForm.formulaMedicamentDetailDTO.splice(index + 1, 0, item);
			},
			addList(list) {
				list.forEach((ele) => {
					let item = {
						...ele,
						drugThirdCode: ele.thirdCode,
						quantity: 1,
						allowDeletion: false,
						payPrice: '',
						totalNum: '',
						totalPrice: ''
					};
					this.tableCount(item);
					this.tabForm.formulaMedicamentDetailDTO.unshift(item);
				});
			},
			// 删除商品
			delRow(index) {
				this.tabForm.formulaMedicamentDetailDTO.splice(index, 1);
			},
			sortRow(index1, index2) {
				let arr = [...this.tabForm.formulaMedicamentDetailDTO]
				;[arr[index1], arr[index2]] = [arr[index2], arr[index1]];
				this.tabForm.formulaMedicamentDetailDTO = arr;
			},
			// 打开药品弹窗
			openDialog() {
				this.goods_id = this.tabForm.formulaMedicamentDetailDTO.map((i) => {
					return i.drugCode;
				});
				this.addGoodsShow = true;
			},
			// 药品数量change
			quantityChnage(row) {
				if (row.quantity === '') return;
				// let reg = /^(\+?[1-9][0-9]*)$/;
				// if (!reg.test(row.quantity)) {
				//   this.$message({
				//     message: '只能正整数',
				//     type: 'warning'
				//   });
				//   row.quantity = '';
				//   return;
				// }
				this.tableCount(row);
			},
			// 计算
			tableCount(row) {
				// 添加不同数量规则下的处理 quantityRule,这里只计算1剂
				//       1剂=N付
				// （1）1剂固定，1剂=3付
				// 当饮片阿胶 1付= 10克时；1剂 阿胶的数量=10克
				// （2）1.5剂固定，1剂=3付
				// 当饮片阿胶 1付= 10克时；1剂 阿胶的数量=10克*3=30克；1.5剂=30克；
				// （3）1剂和1.5剂固定，1剂=3付
				// 当饮片阿胶 1付= 10克时；1剂 阿胶的数量=1.5剂=10克；
				// （4）不填写，1剂=3付
				// 当饮片阿胶 1付= 10克时；1剂 阿胶的数量=10克*3=30克；1.5剂=30*1.5=45克；

				row.payPrice = ((row.drugPrice || 0) * row.quantity).toFixed(2);
				let quantity_rule_name = this.options.dimensionTypes.find((item) => item.id === row.quantityRule)?.dictValue;
				console.log(quantity_rule_name);
				if ((row.drugTypeName == '辅料' || row.drug_type_name == '辅料') && (quantity_rule_name == '1剂固定' || quantity_rule_name == '1剂和1.5剂固定')) {
					row.totalNum = row.quantity;
				} else {
					row.totalNum = parseInt(row.quantity * (this.tabForm.oneMedication || 0) * 100) / 100;
				}
				row.totalPrice = ((row.totalNum || 0) * (row.drugPrice || 0)).toFixed(2);

				this.$nextTick(() => {
					this.$forceUpdate();
				});
			},
			// 汇总
			getSummaries(param) {
				const { columns, data } = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '';
						return;
					}
					const values = data.map((item) => Number(item[column.property]));
					if (column.property == 'payPrice' || column.property == 'totalNum' || column.property == 'totalPrice') {
						sums[index] = values.reduce((prev, curr) => {
							const value = Number(curr);
							if (!isNaN(value)) {
								return prev + curr;
							} else {
								return prev;
							}
						}, 0);
					} else {
						sums[index] = '';
					}
				});
				return sums;
			},
			// 提交
			createDetail(isNew = '') {
				this.$refs.detail.validate((valid) => {
					if (valid) {
						let hintText = this.nameType == '新增' ? `新增${this.detail.formulaName}` : `修改${this.detail.formulaName}`;
						this.hint(hintText, isNew);
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			// 确认提示
			hint(hintText, isNew = '') {
				this.$confirm(`${isNew ? '保存并生成新版本' : hintText}, 是否确认?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
					.then(() => {
						this.submitBrand(isNew);
					})
					.catch(() => {
						this.$message({
							type: 'info',
							message: '已取消'
						});
					});
			},
			// 提交接口
			async submitBrand(isNew = '') {
				let params = {
					...this.detail,
					formulaMedicamentDTO: this.detailData
				};
				// 数量规则、属性，根据id添加文字内容（后端传参需要）↓
				params.formulaMedicamentDTO.forEach((item) => {
					item.formulaMedicamentDetailDTO.forEach((ele, index) => {
						if (ele.attribute) {
							ele.attribute_remark = this.options.dimensionAttribute.find((attribute) => attribute.id == ele.attribute).dictValue;
						} else {
							ele.attribute_remark = '';
						}
						if (ele.quantityRule) {
							ele.quantityRuleRemark = this.options.dimensionTypes.find((rule) => rule.id == ele.quantityRule).dictValue;
						} else {
							ele.quantityRuleRemark = '';
						}
						ele.orderIndex = index;
						console.log(index);
					});
				});
				// 数量规则、属性，根据id添加文字内容（后端传参需要）↑

				if (this.nameType != '新增' || isNew) {
					params.id = this.$route.query.id;
				}
				// 添加维度信息
				params.dimension_id = [params.drugCode];
				params.dimension_type = [];
				params.dimensionList = [];
				console.log(this.dimension);
				if (this.dimension.deptIds?.length) {
					params.dimension_type.push(1);
					this.options.dept
						.filter((item) => this.dimension.deptIds.some((checkedItem) => checkedItem == item.id))
						.forEach((option) => {
							params.dimensionList.push({
								dimension_code: option.id,
								dimension_name: option.dictValue,
								formula_code: params.drugCode,
								dimension_id: params.drugCode,
								dimension_type: 1
							});
						});
				}
				if (this.dimension.diseaseIds?.length) {
					params.dimension_type.push(2);
					this.options.disease
						.filter((item) => this.dimension.diseaseIds.some((checkedItem) => checkedItem == item.id))
						.forEach((option) => {
							params.dimensionList.push({
								dimension_code: option.id,
								dimension_name: option.dictValue,
								formula_code: params.drugCode,
								dimension_id: params.drugCode,
								dimension_type: 2
							});
						});
				}
				if (this.dimension.doctorIds?.length) {
					params.dimension_type.push(3);
					this.options.doctor
						.filter((item) => this.dimension.doctorIds.some((checkedItem) => checkedItem == item.person_id))
						.forEach((option) => {
							params.dimensionList.push({
								dimension_code: option.id || option.person_id,
								dimension_name: option.dictValue || option.person_name,
								formula_code: params.drugCode,
								dimension_id: params.drugCode,
								dimension_type: 3
							});
						});
				}

				console.log(this.nameType);
				console.log(isNew);
				const res = this.nameType == '新增' || (this.nameType != '新增' && isNew) ? await formulaAdd(params) : await registerUpdate(params);
				this.$notification('操作成功', 'success', res.msg);
				this.dialogVisible = false;
				// this.getList();
				this.returnUpper();

				// console.log(res);
			},
			// 返回
			returnUpper() {
				this.$store.dispatch('tagsView/delView', this.$route);
				this.$router.back();
			}
		}
	};
</script>
<style lang="scss" scoped>
	.formulaDetail {
		height: 100%;
		overflow: hidden;
		overflow-y: auto;
	}

	.detailBox {
		position: relative;

		.addBtn {
			position: absolute;
			right: 0px;
			top: 20px;
		}
	}

	::v-deep .el-card {
		overflow: visible;
	}
</style>
